<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $userMapper = new Application_Model_UserMapper();
        $this->view->users = $userMapper->fetchAll();
    }

    public function addAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_User();

        if ($request->isPost() && $form->isValid($request->getPost())) {
            $user = new Application_Model_User($form->getValues());
            $userMapper  = new Application_Model_UserMapper();
            $userMapper->save($user);
            return $this->_helper->redirector('index');
        }

        $this->view->form = $form;
    }

    public function editAction()
    {
        $request = $this->getRequest();
        $id = (int) $request->getParam('id', 0);
        if ($id === 0) {
            return $this->_helper->redirector('index');
        }

        $user = new Application_Model_User();
        $userMapper  = new Application_Model_UserMapper();
        $userMapper->find($id, $user);

        $form = new Application_Form_User();

        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                $user->setOptions($form->getValues());
                $userMapper->save($user);
                return $this->_helper->redirector('index');
            }
        }
        else {
            $form->populate($user->toArray());
        }

        $this->view->form = $form;
    }

    public function task1Action()
    {
        $userForm = new Application_Form_User();
        $companyForm = new Application_Form_Company();

        $this->view->userForm = $userForm;
        $this->view->companyForm = $companyForm;
    }

}

